#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/mman.h>
#include <sys/stat.h>        /* For mode constants */
#include <fcntl.h>           /* For O_* constants */
#include <errno.h>
#include <string.h>

#define LOG_ERR(fmt, ...) printf("[%s:%d %s]ERR: " fmt "\r\n", __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__);

#define SHM_NAME "ctest_shm"
#define SIZE_1G (1024 * 1024 * 1024ULL)
#define SHM_FILE_SIZE (SIZE_1G * 30)

int main()
{
    LOG_ERR("start sizeof(long) = %lu size = %lld", sizeof(long), SHM_FILE_SIZE);

    int fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
    if (fd == -1) {
        LOG_ERR("shm_open fail ret = %d errno = [%d]%s", fd, errno, strerror(errno));
        return 0;
    }

    int ret = ftruncate(fd, SHM_FILE_SIZE);
    if (ret == -1) {
        LOG_ERR("ftruncate fail fd = %d errno = [%d]%s", fd, errno, strerror(errno));
        return 0;
    }

    char *p = mmap(NULL, SHM_FILE_SIZE, PROT_WRITE, MAP_SHARED, fd, 0);
    if (p == MAP_FAILED) {
        LOG_ERR("mmap fail ret = %d errno = [%d]%s", fd, errno, strerror(errno));
        return 0;
    }

    LOG_ERR("mmap success fd = %d size = %lld p = %p", fd, SHM_FILE_SIZE, p);

    (void)sprintf(p, "ctest_posix_shm test_%lu_%d", pthread_self(), 0);

    return 0;
}